import {
  EventSourceMessage,
  fetchEventSource
} from '@microsoft/fetch-event-source';
import {
  Notification,
  MessageBox,
  Message,
  Loading
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from "@/utils/auth";
var parse = require('fast-json-parse')
const baseUrl ='/stream'// process.env.VUE_APP_BASE_API_Stream
export default {

  async queryTextChat(url, params, onMessageCallback, onEndCallback) {
    let eventSourceInstance;
    let doc_list = [];
    try {
      eventSourceInstance = await fetchEventSource(baseUrl + url, {
        method: 'post',
        headers: {
          "Content-Type": 'application/json',
          "Accept": 'application/json',
          Authorization: "Bearer " + getToken(),
        },
        body: JSON.stringify(params),
        onmessage: (ev) => {
          try {
            if (!ev.data) {
              return
            }
            let res = new parse(ev.data); //JSON.parse(ev.data);
            if (res.value.code || res.value.code == 401) {
              if (eventSourceInstance) {
                eventSourceInstance.close();
              }
              MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                store.dispatch('LogOut').then(() => {
                  location.href = '/index';
                })
              })
            }
            if (onMessageCallback) {
              onMessageCallback(res);
            }
          } catch (error) {
            console.log('【onmessage】', error);
          }
        },
        onopen(response) {
          if (response.status !== 200) {
            throw new Error(`Unexpected status code: ${response.status}`);
          }
        },
        onclose(e) {
          console.log('SEE-close', e);
        },
        onerror(err) {
          console.log('SEE-e', err);
          throw err; // 重新抛出错误，以便在外部可以被捕获
        }
      });
      onEndCallback();

    } catch (e) {
      throw e;
    } finally {
      // 确保即使发生异常也能关闭 eventSourceInstance
      if (eventSourceInstance) {
        eventSourceInstance.close();
      }
    }
  }
}
